﻿// Decompiled with JetBrains decompiler
// Type: 我的小工具.IISHelper
// Assembly: 开发辅助工具, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null
// MVID: F78E5980-5E94-4E46-ABDF-DC8C6CBF52AA
// Assembly location: K:\Tools\工具\开发辅助工具庆六一版\开发辅助工具2015-06-01\开发辅助工具.exe

using Microsoft.Web.Administration;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace DotNet.Utilities
{
  public class IISHelper
  {
    public static bool HasInstalled()
    {
      return true;
    }

    public static int GetIISVersionByDri(string domainname)
    {
      try
      {
        if (string.IsNullOrEmpty(domainname))
          domainname = "LOCALHOST";
        return Convert.ToInt32(new DirectoryEntry("IIS://" + domainname + "/W3SVC/INFO").Properties["MajorIISVersionNumber"].Value);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public static int GetIISMajorVersion()
    {
      try
      {
        string localMachineKeyValue = RegistryHelper.GetLocalMachineKeyValue("SOFTWARE\\Microsoft\\InetStp", "MajorVersion");
        if (string.IsNullOrEmpty(localMachineKeyValue))
          throw new Exception("本地服务器未安装IIS。");
        int result = -1;
        if (int.TryParse(localMachineKeyValue, out result))
          return result;
        throw new Exception("本地服务器未安装IIS。");
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public static Dictionary<string, SiteObj> GetSiteNames()
    {
      Dictionary<string, SiteObj> dictionary = new Dictionary<string, SiteObj>();
      if (IISHelper.GetIISMajorVersion() == 6)
      {
        foreach (ManagementObject managementObject in new ManagementObjectSearcher("root\\MicrosoftIISv2", "SELECT * FROM IIsWebServerSetting").Get())
        {
          SiteObj siteObj = new SiteObj();
          siteObj.SiteName = managementObject["ServerComment"].ToString();
          siteObj.SiteNameQuanPin = siteObj.SiteName.ToUpper();
          siteObj.SiteNameDuanPin = siteObj.SiteName.ToUpper();
          siteObj.PoolName = managementObject["AppPoolId"].ToString();
          ManagementBaseObject[] managementBaseObjectArray = (ManagementBaseObject[]) managementObject["ServerBindings"];
          siteObj.Port = managementBaseObjectArray[0]["Port"].ToString();
          int num = 0;
          for (; dictionary.ContainsKey(siteObj.SiteName); siteObj.SiteName = managementObject["ServerComment"].ToString() + "_" + num.ToString())
            ++num;
          dictionary.Add(siteObj.SiteName, siteObj);
        }
      }
      else
      {
        foreach (Site site in (ConfigurationElementCollectionBase<Site>) new ServerManager().Sites)
        {
          SiteObj siteObj = new SiteObj();
          siteObj.SiteName = site.Name;
          siteObj.SiteNameQuanPin = siteObj.SiteName.ToUpper();
          siteObj.SiteNameDuanPin = siteObj.SiteName.ToUpper();
          siteObj.PoolName = site.Applications.Count > 0 ? site.Applications[0].ApplicationPoolName : "";
          siteObj.Port = site.Bindings[0].EndPoint.Port.ToString();
          siteObj.SitePath = site.Applications.Count > 0 ? site.Applications[0].VirtualDirectories[0].PhysicalPath : "";
          int num = 0;
          for (; dictionary.ContainsKey(siteObj.SiteName); siteObj.SiteName = site.Name + "_" + num.ToString())
            ++num;
          dictionary.Add(siteObj.SiteName, siteObj);
        }
      }
      return dictionary;
    }

    public static List<string> GetSiteNames(string strKeyWord)
    {
      List<string> stringList = new List<string>();
      if (IISHelper.GetIISMajorVersion() == 6)
      {
        foreach (ManagementObject managementObject in new ManagementObjectSearcher("root\\MicrosoftIISv2", "SELECT * FROM IIsWebServerSetting").Get())
          stringList.Add(managementObject["ServerComment"].ToString());
      }
      else
      {
        foreach (Site site in (ConfigurationElementCollectionBase<Site>) new ServerManager().Sites)
        {
          //if (site.Name.ToUpper().Contains(strKeyWord.ToUpper()) || PinyinHelper.GetPinyin(site.Name).ToUpper().Contains(strKeyWord.ToUpper()) || PinyinHelper.GetFirstPinyin(site.Name).ToUpper().Contains(strKeyWord.ToUpper()))
            stringList.Add(site.Name);
        }
      }
      return stringList;
    }

    public static string GetWebSiteNumByName(string siteName)
    {
      Regex regex = new Regex(siteName);
      foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/w3svc").Children)
      {
        if (child.SchemaClassName == "IIsWebServer")
        {
          if (child.Properties["ServerBindings"].Value != null)
          {
            string @string = child.Properties["ServerBindings"].Value.ToString();
            if (string.Equals(siteName, @string, StringComparison.InvariantCultureIgnoreCase))
              return child.Name;
          }
          if (child.Properties["ServerComment"].Value != null)
          {
            string @string = child.Properties["ServerComment"].Value.ToString();
            if (string.Equals(siteName, @string, StringComparison.InvariantCultureIgnoreCase))
              return child.Name;
          }
        }
      }
      return "";
    }

    public static string GetSitePath(string siteName)
    {
      try
      {
        if (IISHelper.GetIISMajorVersion() == 6)
          return new DirectoryEntry(string.Format("IIS://LOCALHOST/W3SVC/{0}/root", (object) IISHelper.GetWebSiteNumByName(siteName))).Properties["Path"].Value.ToString();
        return IISHelper.GetSitePathFor7(siteName);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public static string GetSitePathFor7(string siteName)
    {
      foreach (Site site in (ConfigurationElementCollectionBase<Site>) new ServerManager().Sites)
      {
        if (site.Name.ToLower() == siteName.ToLower())
          return site.Applications[0].VirtualDirectories[0].PhysicalPath;
      }
      return "";
    }

    public static int GetSitePortFor7(string siteName)
    {
      foreach (Site site in (ConfigurationElementCollectionBase<Site>) new ServerManager().Sites)
      {
        if (site.Name.ToLower() == siteName.ToLower())
          return site.Bindings[0].EndPoint.Port;
      }
      return 80;
    }

    public static string GetSitePoolNameFor7(string siteName)
    {
      foreach (Site site in (ConfigurationElementCollectionBase<Site>) new ServerManager().Sites)
      {
        if (site.Name.ToLower() == siteName.ToLower() && site.Applications.Count > 0)
          return site.Applications[0].ApplicationPoolName;
      }
      return "";
    }

    public static List<string> GetSiteMimeList(string siteName)
    {
      string webSiteNumByName = IISHelper.GetWebSiteNumByName(siteName);
      List<string> stringList = new List<string>();
      foreach (object obj in (CollectionBase) new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/root", (object) webSiteNumByName)).Properties["MimeMap"])
        ;
      return stringList;
    }

    public static List<string> GetSiteMimeListFor7(string siteName)
    {
      List<string> stringList = new List<string>();
      foreach (ConfigurationElement configurationElement in (ConfigurationElementCollectionBase<ConfigurationElement>) new ServerManager().GetWebConfiguration(siteName).GetSection("system.webServer/staticContent").GetCollection().GetCollection())
        stringList.Add(configurationElement.GetAttributeValue("fileExtension").ToString() + "|" + configurationElement.GetAttributeValue("mimeType"));
      return stringList;
    }

    public static List<string> GetSiteScriptList(string siteName)
    {
      string webSiteNumByName = IISHelper.GetWebSiteNumByName(siteName);
      List<string> stringList = new List<string>();
      foreach (object obj in (CollectionBase) new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/root", (object) webSiteNumByName)).Properties["ScriptMaps"])
        stringList.Add(obj.ToString());
      return stringList;
    }

    public static List<string> GetSiteScriptListFor7(string siteName)
    {
      IISHelper.GetWebSiteNumByName(siteName);
      List<string> stringList = new List<string>();
      foreach (ConfigurationElement configurationElement in (ConfigurationElementCollectionBase<ConfigurationElement>) new ServerManager().GetWebConfiguration(siteName).GetSection("system.webServer/handlers").GetCollection())
        stringList.Add(configurationElement.GetAttributeValue("name").ToString() + "|" + configurationElement.GetAttributeValue("path") + "|" + configurationElement.GetAttributeValue("scriptProcessor"));
      return stringList;
    }

    public static bool CheckRootScriptIsHave(string scriptName)
    {
      foreach (ConfigurationElement configurationElement in (ConfigurationElementCollectionBase<ConfigurationElement>) new ServerManager().GetApplicationHostConfiguration().GetSection("system.webServer/handlers").GetCollection())
      {
        if (scriptName.ToLower() == configurationElement.GetAttributeValue("name").ToString().ToLower())
          return true;
      }
      return false;
    }

    public static List<string> GetSiteHttpHeadList(string siteName)
    {
      string webSiteNumByName = IISHelper.GetWebSiteNumByName(siteName);
      List<string> stringList = new List<string>();
      foreach (object obj in (CollectionBase) new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/root", (object) webSiteNumByName)).Properties["HttpCustomHeaders"])
        stringList.Add(obj.ToString());
      return stringList;
    }

    public static bool CheckIIS6()
    {
      try
      {
        new DirectoryEntry("IIS://localhost/w3svc").Children.GetEnumerator();
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }

    public static string GetNewWebSiteID()
    {
      int num1 = 0;
      foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/w3svc").Children)
      {
        if (child.SchemaClassName == "IIsWebServer")
        {
          child.Properties["ServerComment"].Value.ToString();
          int int32 = Convert.ToInt32(child.Name);
          if (num1 < int32)
            num1 = int32;
        }
      }
      if (num1 < 10)
        num1 = 10;
      int num2;
      return Convert.ToString(num2 = num1 + 1);
    }

    public static bool IsExistSite(string strSiteName)
    {
      bool flag = false;
      foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/w3svc").Children)
      {
        if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value != null && child.Properties["ServerComment"].Value.ToString().ToLower() == strSiteName.ToLower())
          flag = true;
      }
      return flag;
    }

   

    public static bool DelSite(string WebSiteName)
    {
      try
      {
        string webSiteNumByName = IISHelper.GetWebSiteNumByName(WebSiteName);
        if (webSiteNumByName == null)
          return false;
        DirectoryEntry directoryEntry1 = new DirectoryEntry("IIS://localhost/W3SVC");
        DirectoryEntry directoryEntry2 = new DirectoryEntry();
        directoryEntry1.RefreshCache();
        DirectoryEntry entry = directoryEntry1.Children.Find(webSiteNumByName, "IIsWebServer");
        directoryEntry1.Children.Remove(entry);
        directoryEntry1.CommitChanges();
        directoryEntry1.Close();
        return true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public static Dictionary<string, int> GetAppPoolName()
    {
      // int num = util.Is64BitProcess() ? 64 : 32;
      int num = 64;
      Dictionary<string, int> dictionary = new Dictionary<string, int>();
      try
      {
        foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children)
        {
          if (child.Properties.Contains("Enable32BitAppOnWin64") && child.Properties["Enable32BitAppOnWin64"].Value.Equals((object) true))
            dictionary.Add(child.Name, 32);
          else
            dictionary.Add(child.Name, num);
        }
      }
      catch(Exception ex)
      {
      }
      return dictionary;
    }

    public static bool IsAppPoolName(string AppPoolName)
    {
      bool flag = false;
      foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children)
      {
        if (child.Name.ToLower() == AppPoolName.ToLower())
          flag = true;
      }
      return flag;
    }

    public static bool DeleteAppPool(string AppPoolName)
    {
      bool flag = false;
      foreach (DirectoryEntry child in new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children)
      {
        if (child.Name.ToLower() == AppPoolName.ToLower())
        {
          try
          {
            child.DeleteTree();
            flag = true;
          }
          catch
          {
            flag = false;
          }
        }
      }
      return flag;
    }

    public static bool CreateAppPool(string sAppPoolName, bool Enable32BitAppOnWin64, int OSBit)
    {
      try
      {
        if (IISHelper.IsAppPoolName(sAppPoolName))
          IISHelper.DeleteAppPool(sAppPoolName);
        DirectoryEntry directoryEntry = new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children.Add(sAppPoolName, "IIsApplicationPool");
        directoryEntry.Properties["AppPoolIdentityType"].Value = (object) 2;
        if (IISHelper.GetIISMajorVersion() > 6)
        {
          if (Enable32BitAppOnWin64 && OSBit == 64)
            directoryEntry.Properties["Enable32BitAppOnWin64"].Value = (object) true;
          directoryEntry.Properties["ManagedRuntimeVersion"].Value = (object) "v2.0";
          directoryEntry.Properties["ManagedPipelineMode"].Value = (object) 1;
          directoryEntry.Properties["PingingEnabled"].Value = (object)false;
        }
        directoryEntry.CommitChanges();
        return true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public static bool RecycleAppPool(string AppPoolName)
    {
      try
      {
        DirectoryEntry directoryEntry = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
        directoryEntry.Children.Find(AppPoolName, "IIsApplicationPool").Invoke("Recycle", (object[]) null);
        directoryEntry.CommitChanges();
        directoryEntry.Close();
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }

    public static bool AddMime()
    {
      return true;
    }

    public static bool AddScript()
    {
      return true;
    }

    public static string GetDefaultSitePath(string siteName)
    {
      DriveInfo[] drives = DriveInfo.GetDrives();
      string str = "C:\\";
      long num = 0;
      foreach (DriveInfo driveInfo in drives)
      {
        if (driveInfo.IsReady && driveInfo.DriveType == DriveType.Fixed && driveInfo.TotalFreeSpace > num)
        {
          num = driveInfo.TotalFreeSpace;
          str = driveInfo.Name;
        }
      }
      return string.Format("{0}Mysoft\\{1}", (object) str, (object) siteName);
    }

    public static int GetOSBit()
    {
      try
      {
        string s = string.Empty;
        foreach (ManagementBaseObject managementBaseObject in new ManagementObjectSearcher(new ManagementScope("\\\\localhost", new ConnectionOptions()), new ObjectQuery("select AddressWidth from Win32_Processor")).Get())
          s = managementBaseObject["AddressWidth"].ToString();
        return int.Parse(s) == 32 ? 32 : 64;
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.ToString());
        return 32;
      }
    }

    public static bool CheckIISSiteName(string siteName, out string errorMsg)
    {
      if (string.IsNullOrEmpty(siteName) || string.IsNullOrEmpty(siteName.Trim()))
      {
        errorMsg = "站点名称不能为空。";
        return false;
      }
      if (!new Regex("^[A-Za-z0-9_()-]+$").IsMatch(siteName))
      {
        errorMsg = "站点名称只能包含英文、数字、下划线、小括号和横杠。";
        return false;
      }
      if (!new Regex("^[A-Za-z0-9]+\\S+$").IsMatch(siteName))
      {
        errorMsg = "站点名称必须以字母或数字开头。";
        return false;
      }
      errorMsg = string.Empty;
      return true;
    }

    public static bool CreateFTPXml()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection authorizationSection = config.GetSection("system.ftpServer/security/authorization", "ftp");
            ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();

            ConfigurationElement addElement = authorizationCollection.CreateElement("add");
            addElement["accessType"] = @"Allow";
            addElement["roles"] = @"administrators";
            addElement["permissions"] = @"Read, Write";
            authorizationCollection.Add(addElement);

            ConfigurationElement addElement1 = authorizationCollection.CreateElement("add");
            addElement1["accessType"] = @"Deny";
            addElement1["users"] = @"guest";
            addElement1["permissions"] = @"Read, Write";
            authorizationCollection.Add(addElement1);

            serverManager.CommitChanges();
        }
        return true;
    }
    public static DirectoryEntry CreateSite(SiteObj siteObj)
    {
        try
        {
            if (IISHelper.IsExistSite(siteObj.SiteName))
                IISHelper.DelSite(siteObj.SiteName);
            DirectoryEntry directoryEntry1 = new DirectoryEntry("IIS://localhost/w3svc").Children.Add(IISHelper.GetNewWebSiteID(), "IIsWebServer");
            directoryEntry1.Properties["ServerComment"].Value = (object)siteObj.SiteName;
            directoryEntry1.Properties["ServerBindings"].Value = (object)string.Format("{0}:{1}:{2}", (object)"", (object)siteObj.Port, (object)"");
            directoryEntry1.Properties["ServerAutoStart"].Value = (object)true;
            DirectoryEntry directoryEntry2 = directoryEntry1.Children.Add("Root", "IIsWebVirtualDir");
            directoryEntry2.Properties["Path"].Value = (object)siteObj.SitePath;
            directoryEntry2.Properties["AccessRead"][0] = (object)true;
            directoryEntry2.Properties["AccessExecute"][0] = (object)false;
            directoryEntry2.Properties["AccessWrite"][0] = (object)false;
            directoryEntry2.Properties["AccessScript"][0] = (object)true;
            directoryEntry2.Properties["EnableDirBrowsing"][0] = (object)false;
            directoryEntry2.Properties["DefaultDoc"][0] = (object)"UserLogin.aspx,Default.aspx";
            directoryEntry2.Properties["AppPoolId"][0] = (object)siteObj.SiteName;
            directoryEntry2.Properties["AspEnableParentPaths"][0] = (object)true;
            if (IISHelper.GetIISMajorVersion() < 7)
            {
                string str = ".asp,[system32]\\asp.dll,5,GET,HEAD,POST,TRACE\r\n.cer,[system32]\\asp.dll,5,GET,HEAD,POST,TRACE\r\n.cdx,[system32]\\asp.dll,5,GET,HEAD,POST,TRACE\r\n.asa,[system32]\\asp.dll,5,GET,HEAD,POST,TRACE\r\n.idc,[system32]\\httpodbc.dll,5,GET,POST\r\n.shtm,[system32]\\ssinc.dll,5,GET,POST\r\n.shtml,[system32]\\ssinc.dll,5,GET,POST\r\n.stm,[system32]\\ssinc.dll,5,GET,POST\r\n.asax,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.ascx,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.ashx,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.asmx,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.aspx,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.axd,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.vsdisco,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.rem,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.soap,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.config,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.cs,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.csproj,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.vb,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.vbproj,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.webinfo,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.licx,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.resx,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.resources,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.xoml,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.rules,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.master,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.skin,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.compiled,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.browser,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.mdb,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.jsl,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.vjsproj,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.sitemap,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.msgx,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.ad,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.dd,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.ldd,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.sd,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.cd,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.adprototype,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.lddprototype,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.sdm,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.sdmDocument,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.ldb,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.svc,[netpath]\\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG\r\n.mdf,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.ldf,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.java,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.exclude,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG\r\n.refresh,[netpath]\\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG";
                string newValue1 = Environment.SystemDirectory + "\\inetsrv";
                string newValue2 = RuntimeEnvironment.GetRuntimeDirectory().TrimEnd('\\');
                if (IISHelper.GetOSBit() == 64 && newValue2.IndexOf("Framework64") == -1)
                    newValue2 = newValue2.Replace("Framework", "Framework64");
                string[] strArray = Regex.Split(str.Replace("[system32]", newValue1).Replace("[netpath]", newValue2), "\r\n");
                directoryEntry2.Properties["ScriptMaps"].Value = (object)strArray;
                directoryEntry2.Properties["AppFriendlyName"][0] = (object)"默认应用程序";
                directoryEntry2.Invoke("AppCreate", (object)true);
            }
            directoryEntry2.CommitChanges();
            directoryEntry1.CommitChanges();
            return directoryEntry2;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public static bool CreateFTP()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            if (IISHelper.IsExistSite("MyFtpSite"))
                IISHelper.DelSite("MyFtpSite");
            Configuration config = serverManager.GetApplicationHostConfiguration();

            ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");

            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

            ConfigurationElement siteElement = sitesCollection.CreateElement("site");
            siteElement["name"] = @"MyFtpSite";
            int s = 8;
            siteElement["id"] = s;

            ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");

            ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
            bindingElement["protocol"] = @"ftp";
            bindingElement["bindingInformation"] = @"10.5.105.100:2001:";
            bindingsCollection.Add(bindingElement);

            ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");

            ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");

            ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
            // sslElement["serverCertHash"] = @"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
            sslElement["controlChannelPolicy"] = @"SslAllow";
            sslElement["dataChannelPolicy"] = @"SslAllow";

            ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");

            ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
            basicAuthenticationElement["enabled"] = true;

            ConfigurationElementCollection siteCollection = siteElement.GetCollection();

            ConfigurationElement applicationElement = siteCollection.CreateElement("application");
            applicationElement["path"] = @"/";

            ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();

            ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
            virtualDirectoryElement["path"] = @"/";
            virtualDirectoryElement["physicalPath"] = @"F:\MyFtp";
            applicationCollection.Add(virtualDirectoryElement);
            siteCollection.Add(applicationElement);
            sitesCollection.Add(siteElement);

            serverManager.CommitChanges();
            config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection authorizationSection = config.GetSection("system.ftpServer/security/authorization", "MyFtpSite");
            ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();

            ConfigurationElement addElement = authorizationCollection.CreateElement("add");
            addElement["accessType"] = @"Allow";
            addElement["roles"] = @"administrators";
            addElement["permissions"] = @"Read, Write";
            authorizationCollection.Add(addElement);

            //ConfigurationElement addElement1 = authorizationCollection.CreateElement("add");
            //addElement1["accessType"] = @"Allow";
            //addElement1["users"] = @"yudm";
            //addElement1["permissions"] = @"Read, Write";
            //authorizationCollection.Add(addElement1);

            serverManager.CommitChanges();
        }

        return true;
    }
  }
    public class SiteObj
    {
        public string SiteName { get; set; }

        public string SiteNameQuanPin { get; set; }

        public string SiteNameDuanPin { get; set; }

        public string Port { get; set; }

        public string SitePath { get; set; }

        public string PoolName { get; set; }
    }
    public class RegistryHelper
    {
        public static string GetLocalMachineKeyValue(string path, string keyName)
        {
            object obj = Registry.LocalMachine.OpenSubKey(path, true).GetValue(keyName);
            return obj == null ? "" : obj.ToString();
        }
    }
}
